package com.match.competition_apply.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.match.competition_apply.client.CourseClient;
import com.match.competition_apply.entity.CompetitionInfo;
import com.match.competition_apply.entity.CompetitionSignUp;
import com.match.competition_apply.entity.vo.SignUpQuery;
import com.match.competition_apply.entity.vo.StudentSignUpVo;
import com.match.competition_apply.mapper.CompetitionSignUpMapper;
import com.match.competition_apply.service.CompetitionInfoService;
import com.match.competition_apply.service.CompetitionSignUpService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.match.competition_apply.utils.CompetitionExcelByHutoolUtils;
import com.match.entity.baseEntity.Student;
import com.match.entity.baseEntity.Teacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author AdiosF
 * @since 2021-11-03
 */
@Service
public class CompetitionSignUpServiceImpl extends ServiceImpl<CompetitionSignUpMapper, CompetitionSignUp> implements CompetitionSignUpService {

    @Autowired
    CompetitionInfoService competitionInfoService;
    @Autowired
    CourseClient courseClient;


    /**
     * 保存报名信息
     * @param competitionSignUp
     * @return
     */
    @Override
    public CompetitionSignUp saveSignInfo(CompetitionSignUp competitionSignUp) {
        baseMapper.insert(competitionSignUp);
        return competitionSignUp;
    }

    /**
     * 分页条件查询报名信息
     * @param current
     * @param limit
     * @param signUpQuery
     * @return
     */
    @Override
    public Map<String, Object> getSignUpPageList(long current, long limit, SignUpQuery signUpQuery) {
        //构造Page对象
        Page<CompetitionSignUp> competitionSignUpPage=new Page<>(current,limit);
        //封装查询条件
        QueryWrapper<CompetitionSignUp> competitionSignUpQueryWrapper=new QueryWrapper<>();
        String string = signUpQuery.getRoles().toString();
        if (!string.contains("系统管理员")){
            if (!StringUtils.isEmpty(signUpQuery.getTeacherNumber())){
                competitionSignUpQueryWrapper.eq("teacher_number",signUpQuery.getTeacherNumber());
            }
        }
        if (StringUtils.isEmpty(signUpQuery.getStates()) && string.contains("系统管理员")){
                competitionSignUpQueryWrapper.notIn("states","0");
        }
        if (!StringUtils.isEmpty(signUpQuery.getStates())){
                competitionSignUpQueryWrapper.in("states","0","2","3","4","5");
        }
        competitionSignUpQueryWrapper.orderByAsc("gmt_create");
        baseMapper.selectPage(competitionSignUpPage, competitionSignUpQueryWrapper);

        Map<String,Object> map=new HashMap<>();
        long total = competitionSignUpPage.getTotal();
        List<CompetitionSignUp> records = competitionSignUpPage.getRecords();
        for (CompetitionSignUp competitionSignUp : records) {
            CompetitionInfo byId = competitionInfoService.getById(competitionSignUp.getGroupId());
            //设置组ID为空
            byId.setId(null);
            byId.setBegintime(CompetitionExcelByHutoolUtils.parseTimeToString(byId.getCompetitionBegin()));
            byId.setEndtime(CompetitionExcelByHutoolUtils.parseTimeToString(byId.getCompetitionEnd()));
            competitionSignUp.setCompetitionInfo(byId);

            //设置第一指导老师
            if (!StringUtils.isEmpty(competitionSignUp.getAdviserOne())){
                Teacher teacher=baseMapper.getTeacher(competitionSignUp.getAdviserOne());
                teacher.setPassword(null);
                competitionSignUp.setOneTeacher(teacher);
            }
            if (!StringUtils.isEmpty(competitionSignUp.getAdviserTwo())){
                Teacher teacher=baseMapper.getTeacher(competitionSignUp.getAdviserTwo());
                teacher.setPassword(null);
                competitionSignUp.setTwoTeacher(teacher);
            }

            //设置队长姓名以及学号
            if (!StringUtils.isEmpty(competitionSignUp.getStudentNumber())){
                String[] split = competitionSignUp.getStudentNumber().split(",");
                if (!StringUtils.isEmpty(split[0])){
                    if (split.length>1){
                        Student student = baseMapper.getStudent(split[0]);
                        competitionSignUp.setStudentLeader(student);
                        //设置组员姓名以及学号
                        competitionSignUp.setGroupMembersName(getGroupNames(competitionSignUp.getStudentNumber()));
                        List<String> membersNumbers=getMembersNumbers(split);
                        competitionSignUp.setGroupMembersNumbers(membersNumbers);
                    }else {
                        Student student = baseMapper.getStudent(split[0]);
                        competitionSignUp.setStudentLeader(student);
                        competitionSignUp.setGroupMembersName(student.getName());
                    }
                }else {
                    //暂未确定队长
                    competitionSignUp.setGroupMembersName(getGroupNames(competitionSignUp.getStudentNumber()));
                    List<String> membersNumbers=getMembersNumbers(split);
                    competitionSignUp.setGroupMembersNumbers(membersNumbers);
                }
            }
            if (!StringUtils.isEmpty(competitionSignUp.getTeacherNumber())){
                competitionSignUp.setOrderTeacher(baseMapper.getTeacher(competitionSignUp.getTeacherNumber()));
            }
        }
        map.put("total",total);
        map.put("records",records);
        return map;
    }


    /**
     * 更新学生参赛数
     * @param studentNumber
     */
    @Override
    public void upDateStudentCount(String studentNumber) {
          baseMapper.updateStudentCountNumber(studentNumber);
    }


    /**
     * 根据组别Id移除中间表信息
     * @param signUpId
     */
    @Override
    public void removeStudentGrout(String signUpId) {
        baseMapper.deleteNumberGroutByGroutId(signUpId);
    }

    /**
     * 获取队长姓名
     * @param leaderNumber
     * @return
     */
    @Override
    public String getLeaderNameByNumber(String leaderNumber) {
        String teamLeaderName = baseMapper.getTeamLeaderName(leaderNumber);
        return teamLeaderName;
    }

    /**
     * 获取组员姓名
     * @param studentNumber
     * @return
     */
    @Override
    public String getGroupMembersNameByNumber(String studentNumber) {
        String groupNames = this.getGroupNames(studentNumber);
        return groupNames;
    }

    /**
     * 获取指导老师姓名
     * @param adviserOne
     */
    @Override
    public String getTeacherNameByNumber(String adviserOne) {
        String adviserName = baseMapper.getAdviserOne(adviserOne);
        return adviserName;
    }

    /**
     * 更新报名状态
     * @param signUpId
     * @param states
     */
    @Override
    public void updateSignUpStates(String signUpId, Integer states,String backInfo) {
        baseMapper.updateSignUpStates(signUpId,states,backInfo);
    }

    /**
     * 得到驳回信息
     * @param signUpId
     * @return
     */
    @Override
    public String getBackInfoById(String signUpId) {
        String backInfo=baseMapper.getBackInfo(signUpId);
        return backInfo;
    }

    /**
     * 得到学生信息
     * @param studentNumber
     * @return Student
     */
    @Override
    public Student getStudentByNumber(String studentNumber) {
        Student student=baseMapper.getStudent(studentNumber);
        return student;
    }

    /**
     * 根据报名ID获取报名信息
     * @param competitionSignUpServiceById
     * @return
     */
    @Override
    public CompetitionSignUp getSignUpInfo(CompetitionSignUp competitionSignUpServiceById) {
        //设置第一指导老师
        if (!StringUtils.isEmpty(competitionSignUpServiceById.getAdviserOne())){
            competitionSignUpServiceById.setOneTeacher(baseMapper.getTeacher(competitionSignUpServiceById.getAdviserOne()));
        }
        if (!StringUtils.isEmpty(competitionSignUpServiceById.getAdviserTwo())){
            competitionSignUpServiceById.setTwoTeacher(baseMapper.getTeacher(competitionSignUpServiceById.getAdviserTwo()));
        }
        if (!StringUtils.isEmpty(competitionSignUpServiceById.getStudentNumber())){
            String studentNumber = competitionSignUpServiceById.getStudentNumber();
            String[] split = studentNumber.split(",");
            if (!StringUtils.isEmpty(split[0])){
                if (split.length>1){
                    //设置队长学号
                    competitionSignUpServiceById.setStudentLeader(baseMapper.getStudent(split[0]));
                    competitionSignUpServiceById.setGroupMembersNumbers(getMembersNumbers(split));
                    competitionSignUpServiceById.setGroupMembersName(getGroupNames(competitionSignUpServiceById.getStudentNumber()));
                }else {
                    competitionSignUpServiceById.setStudentLeader(baseMapper.getStudent(split[0]));
                }
            }else {
                //设置组员学号
                competitionSignUpServiceById.setGroupMembersNumbers(getMembersNumbers(split));
                competitionSignUpServiceById.setGroupMembersName(getGroupNames(competitionSignUpServiceById.getStudentNumber()));
            }
            return competitionSignUpServiceById;
        }else {
            return competitionSignUpServiceById;
        }
    }


    /**
     * 学生-分页查询自己已报名的项目
     *
     * @param current
     * @param limit
     * @param studentSignUpVo
     * @return
     */
    @Override
    public Map<String, Object> getStudentSignUpList(long current, long limit, StudentSignUpVo studentSignUpVo) {
        //根据学生学号查询学生所有的组别ID
        List<String> groupId=baseMapper.getStudentGroupId(studentSignUpVo.getNumber());
        //构造Page对象
        Page<CompetitionSignUp> competitionSignUpPage=new Page<>(current,limit);
        //封装查询条件
        QueryWrapper<CompetitionSignUp> competitionSignUpQueryWrapper=new QueryWrapper<>();
        if (!StringUtils.isEmpty(studentSignUpVo.getAdviser())){
            competitionSignUpQueryWrapper.eq("adviser_one",studentSignUpVo.getAdviser());
        }
        if (!StringUtils.isEmpty(studentSignUpVo.getYearTime())){
            String begin=studentSignUpVo.getYearTime()+"-01-01 00:00:00";
            String end=studentSignUpVo.getYearTime()+"-12-31 00:00:00";
            competitionSignUpQueryWrapper.between("gmt_create",begin,end);
        }
        competitionSignUpQueryWrapper.in("id",groupId);
        competitionSignUpQueryWrapper.orderByAsc("gmt_create");
        baseMapper.selectPage(competitionSignUpPage, competitionSignUpQueryWrapper);

        Map<String,Object> map=new HashMap<>();
        long total = competitionSignUpPage.getTotal();
        List<CompetitionSignUp> records = competitionSignUpPage.getRecords();
        if (!StringUtils.isEmpty(studentSignUpVo.getNumber())){
            for (CompetitionSignUp record : records) {
                //获取每个学生是否已置换课程
                Integer result=baseMapper.getStudentReplace(studentSignUpVo.getNumber(),record.getId());
                if (result.equals(1)){
                    record.setStates(7);
                }
            }
        }
        for (CompetitionSignUp competitionSignUp : records) {
            CompetitionInfo byId = competitionInfoService.getById(competitionSignUp.getGroupId());
            //设置组ID为空
            byId.setId(null);
            byId.setBegintime(CompetitionExcelByHutoolUtils.parseTimeToString(byId.getCompetitionBegin()));
            byId.setEndtime(CompetitionExcelByHutoolUtils.parseTimeToString(byId.getCompetitionEnd()));
            competitionSignUp.setCompetitionInfo(byId);

            //设置第一指导老师
            if (!StringUtils.isEmpty(competitionSignUp.getAdviserOne())){
                Teacher teacher=baseMapper.getTeacher(competitionSignUp.getAdviserOne());
                teacher.setPassword(null);
                competitionSignUp.setOneTeacher(teacher);
            }
            if (!StringUtils.isEmpty(competitionSignUp.getAdviserTwo())){
                Teacher teacher=baseMapper.getTeacher(competitionSignUp.getAdviserTwo());
                teacher.setPassword(null);
                competitionSignUp.setTwoTeacher(teacher);
            }

            //设置队长姓名以及学号
            if (!StringUtils.isEmpty(competitionSignUp.getStudentNumber())){
                String[] split = competitionSignUp.getStudentNumber().split(",");
                if (!StringUtils.isEmpty(split[0])){
                    if (split.length>1){
                        Student student = baseMapper.getStudent(split[0]);
                        competitionSignUp.setStudentLeader(student);
                        //设置组员姓名以及学号
                        competitionSignUp.setGroupMembersName(getGroupNames(competitionSignUp.getStudentNumber()));
                        List<String> membersNumbers=getMembersNumbers(split);
                        competitionSignUp.setGroupMembersNumbers(membersNumbers);
                    }else {
                        Student student = baseMapper.getStudent(split[0]);
                        competitionSignUp.setStudentLeader(student);
                        competitionSignUp.setGroupMembersName(student.getName());
                    }
                }else {
                    //暂未确定队长
                    competitionSignUp.setGroupMembersName(getGroupNames(competitionSignUp.getStudentNumber()));
                    List<String> membersNumbers=getMembersNumbers(split);
                    competitionSignUp.setGroupMembersNumbers(membersNumbers);
                }
            }
            if (!StringUtils.isEmpty(competitionSignUp.getTeacherNumber())){
                competitionSignUp.setOrderTeacher(baseMapper.getTeacher(competitionSignUp.getTeacherNumber()));
            }
        }
        map.put("total",total);
        map.put("records",records);
        return map;
    }


    //得到组员学号List<String>
    private List<String> getMembersNumbers(String[] split) {
        List<String> stringList=new ArrayList<>();
        for (int i = 1; i < split.length; i++) {
            stringList.add(split[i]);
        }
        return stringList;
    }


    //得到队长姓名
    private String getLeaderName(String studentNumber) {
        if (StringUtils.isEmpty(studentNumber)){
            return null;
        }
        String[] split = studentNumber.split(",");
        if (StringUtils.isEmpty(split[0])){
            return null;
        }else {
            String string=baseMapper.getTeamLeaderName(split[0]);
            return string;
        }
    }
    //得到组员姓名
    private String getGroupNames(String studentNumber) {
        if (StringUtils.isEmpty(studentNumber)){
            return null;
        }
        String[] split = studentNumber.split(",");
        List<String> stringList=new ArrayList<>();
        for (int i = 1; i < split.length; i++) {
            String studentName = baseMapper.getTeamLeaderName(split[i]);
            stringList.add(studentName);
        }
        String str = stringList.stream().collect(Collectors.joining(" 、"));
        return str;
    }

}
